//
//  HJCEmoticonKeyboardViewController.swift
//  表情键盘
//
//  Created by 郝俊聪 on 15/5/24.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit

//cell的id
private let emoticonCellID = "emoticon"

class HJCEmoticonKeyboardViewController: UIViewController {

//    var emoticons = Emoticon.allEmoticonsFromPlist()
    ///定义一个闭包，执行插入表情操作
    var insertEmoticon : ((cell:EmoticonCell)->())?
    
    lazy var emoticons : [Emoticon] = {
            let emoticons = Emoticon.allEmoticonsFromPlist()
            return emoticons
        }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置UI
        setUI()
    }


    ///设置UI
    func setUI(){
        //添加控件
        self.view.addSubview(toolbar)
        self.view.addSubview(emoticonView)
        //设置约束
        setconstrains()
        //注册Cell
        self.registeCollectionViewCell()
    }

    ///定义一个toolbar
    lazy var toolbar : UIToolbar = {
        let tool = UIToolbar(frame: CGRectZero)
        //定义一个数组用于装item
        var itemArray = [UIBarButtonItem]()
        //设置barbuttonItem
        var index = 0
        for title in ["最近","默认","Emoji","浪小花"] {
            //创建
            let spaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            //加入数组中
            itemArray.append(spaceItem)
            
            let barItem = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: "clickToolBarItem")
            itemArray.append(barItem)
            
            if index == 3{
                //创建弹簧item
                let spaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
                //加入数组中
                itemArray.append(spaceItem)
            }
            index++
        }
        //设置items
        tool.items = itemArray
        //返回
        return tool
        }()
    func clickToolBarItem(){
        println("\(__FUNCTION__)")
    }
    ///定义一个collectionView用于装表情
    lazy var emoticonView : UICollectionView = {
        //创建布局
        let layout = UICollectionViewFlowLayout()
        let w = UIScreen.mainScreen().bounds.size.width/7
        layout.itemSize = CGSizeMake(w, w)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.sectionInset = UIEdgeInsetsMake(4, 0, 0, 0)
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        //创建collectionView
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        collectionView.pagingEnabled = true
        collectionView.backgroundColor = UIColor.whiteColor()
        //设置数据源和代理
        collectionView.dataSource = self
        collectionView.delegate = self

        //返回
        return collectionView
        }()
    
    ///设置约束
    func setconstrains(){
        toolbar.setTranslatesAutoresizingMaskIntoConstraints(false)
        emoticonView.setTranslatesAutoresizingMaskIntoConstraints(false)
        //定义一个数组用于接收约束
        var arrayM = [AnyObject]()
        
        arrayM += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["toolbar":toolbar])
        arrayM += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[emoticonView]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["emoticonView":emoticonView])
        arrayM += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[emoticonView]-0-[toolbar(44)]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["emoticonView":emoticonView,"toolbar":toolbar])
       
        //将约束添加到父控件
        self.view.addConstraints(arrayM)
    }
    ///注册cell
    func registeCollectionViewCell(){
         emoticonView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: emoticonCellID)
    }

}
//MARK:- UICollectionViewDataSource,UICollectionViewDelegate
extension HJCEmoticonKeyboardViewController : UICollectionViewDataSource,UICollectionViewDelegate{
  
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emoticonCellID, forIndexPath: indexPath) as! EmoticonCell
        
        cell.emoticon = emoticons[indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //文本textView的控制器插入表情（执行闭包）
        if let cell = collectionView.cellForItemAtIndexPath(indexPath){
            //执行
            self.insertEmoticon!(cell: (cell as! EmoticonCell))
        }
    }

}

///MARK:- EmoticonCell
class EmoticonCell: UICollectionViewCell {
    //拥有个emoticon属性，设置的时候初始化数据
    var emoticon : Emoticon?{
        didSet{
            //如果是删除按钮
            if emoticon!.isDelete {
                imageButton.setTitle("删", forState: UIControlState.Normal)
                imageButton.setImage(nil,forState: UIControlState.Normal)
                return
            }
            //如果是空按钮
            if emoticon!.isEmpty {
                imageButton.setTitle("空", forState: UIControlState.Normal)
                imageButton.setImage(nil,forState: UIControlState.Normal)
                return
            }
            //如果是图片按钮
            if emoticon!.png != nil{
                imageButton.setImage(UIImage(contentsOfFile: emoticon!.png!),forState: UIControlState.Normal)
                imageButton.setTitle(nil, forState: UIControlState.Normal)
            }else if emoticon!.code != nil{
                //emoji按钮
                imageButton.setTitle(emoticon?.emojiStr, forState: UIControlState.Normal)
                imageButton.setImage(nil,forState: UIControlState.Normal)
            }
        }
    }
    
    lazy var imageButton : UIButton = {
        let imageButton = UIButton()
        imageButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        //禁止按钮交互，将交互丢给cell
        imageButton.userInteractionEnabled = false
        return imageButton
        }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.contentView.addSubview(imageButton)
        imageButton.frame = CGRectInset(self.bounds, 2, 2)
        
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
}
